package br.great.DAO;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import br.great.classes.CenterDistance_TrackpointList;
import br.great.beans.Collection;
import br.great.beans.TrackPoint;
import br.great.beans.User;
import br.great.beans.Collection_ContentAnnotation;
import br.great.beans.Tag;
import br.great.typeTags.Type_Tags;

/** 
* PhotoMap
* Copyright (c) 2007-2008 STEAMER - LIG, All rights reserved.
*/

/**
 * @author Developpement of PhotoMap
 */
public class DAO_Collection {
    int idCollection;
    private double weight = 1;
    
    private static volatile DAO_Collection instaceDAO_Collection = new DAO_Collection();
    
    /** The private constructor of DAO_Collection for singleton
    */
    private DAO_Collection(){
    }
    
    /** The method for get the instance of the class DAO_Collection
    * @return DAO_Collection instaceDAO_Collection
    */
    public static DAO_Collection getInstance() {
        //if(instaceDAO_Collection==null)
           synchronized(DAO_Collection.class) {
             if (instaceDAO_Collection == null)
               instaceDAO_Collection = new DAO_Collection();
           }
        return instaceDAO_Collection;
    }
    
    /** method description
    * @param var signification
    * @exception exception class name
    * @return return_value return signification
    * @see package.class#member label
    */

    public int insertCollection(Collection collection, User user){
        // For insert the information in table collection
        // String insertCollection = "insert into Collection values(nextval('seqmax_collection')+15,'"+collection.getLOGIN()+"','"+collection.getUsersFOAFProfil()+"','"+collection.getName()+"' ,'"+collection.getURIImageSymbol()+"');";
        String insertCollection = "insert into Collection values(nextval('seqmax_collection'),'"+user.getLogin()+"','"+collection.getName()+"','"+collection.getURI()+"',"+collection.getPhotos().size()+",'"+collection.getURIImageSymbol()+"', 'true');";
        // For get the ID of the insert
        String getIdCollection = "select max(id_collection) from collection;";
        // Open the connection of the Database
        PgConnect conn = PgConnect.getInstance();

       
        try {
             // Do the insertion
        conn.executeInsert(insertCollection);
        // Get the information
        ResultSet rs = conn.executeQuery(getIdCollection);
            while (rs.next()) {
                idCollection = rs.getInt("max");
            }
        } catch (SQLException ex) {
            Logger.getLogger(DAO_Collection.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        // Get the TrackPointList
        Vector<TrackPoint> vtp = collection.getTrackPointList();
        
        // Clculer Center and Distance to corner
        CenterDistance_TrackpointList cdt = new CenterDistance_TrackpointList();
        String[] stb = cdt.getCenterAndDistance(vtp);
        
        Calendar cal=Calendar.getInstance();
        Timestamp timeInitial= new Timestamp(collection.getBegin().getTime());
        cal.setTime(collection.getBegin());
        
        cal.setTimeInMillis(timeInitial.getTime());
        
        Timestamp timeFinal= new Timestamp(collection.getEnd().getTime());
        // For insert into table Event_Collection
        String insertEventCollection = "insert into Event_Collection values("+idCollection+",'"+stb[0]+"','"+stb[1]+"','"+timeInitial.toString()+"','"+timeFinal.toString()+"');";
        // Do the insertion in the table Event_Collection
        try {
        conn.executeInsert(insertEventCollection);
        }catch(Exception e){
            
        }
        
        // insertion des trackpoints
        DAO_Trackpoint dtp = DAO_Trackpoint.getInstance();
        dtp.insertTrackpointVector(idCollection, vtp);
        
        // insertion of the Collection_ContentAnnotation return the ID "idContentA"
        Collection_ContentAnnotation ca = new Collection_ContentAnnotation();
        ca.setPHRASE(collection.getContentAnnotation());
        int idContentA = DAO_ContentAnnotation.getInstance().insertAnnotation(ca);
        
        // insert the tags in the table and return the IDs of the Tags by Vector "vID_Tag"
        Vector<Tag> vTag = collection.getTags();
        DAO_TAG dt = DAO_TAG.getInstance();
        for (int itag=0; itag<vTag.size();itag++){
            Tag tag = (Tag) vTag.elementAt(itag);
            tag.setTAG_TYPE(new Type_Tags().getManuel());
             tag.setTAG_SUB_TYPE(new Type_Tags().getManuel());
            tag.setTAG_VALUE(tag.getTAG_VALUE());
            tag.setTAG_ID(dt.insertTAG(tag));//insertion des tags
        }
        
        // insert the values in ContentAnnotationHasTag
        DAO_ContentAnnotationHasTag dcaht = DAO_ContentAnnotationHasTag.getInstance();
        for(int iCAHT=0; iCAHT<vTag.size(); iCAHT++){
            int id_Tag = ((Tag)vTag.elementAt(iCAHT)).getTAG_ID();
            dcaht.insertContentAnnotationHasTag(id_Tag, idContentA, weight);
        }
        
        // insert the values in ContentAnnotationHasTag
        DAO_CollectionHasContentAnnotation dcaca = DAO_CollectionHasContentAnnotation.getInstance();
        dcaca.insertCollectionHasContentAnnotation(idContentA, idCollection);
        
        // update the nb of new collections
        DAO_User du = DAO_User.getInstance();
        du.updateNumberNewCollection(user);
        
        conn.Close();
        return idCollection;
    }
    
    public Collection getCollection(int idCollection) {
        Collection c = new Collection();
        String getCollection = "select distinct * from collection c, event_collection ec where c.id_collection = "+idCollection+" and c.id_collection=ec.id_collection;";
        PgConnect conn = PgConnect.getInstance();
        ResultSet rs = conn.executeQuery(getCollection);

        try {
            if (rs.next()) {
                c.setBegin(rs.getTimestamp("time_initial"));
                c.setEnd(rs.getTimestamp("time_final"));
                c.setName(rs.getString("name_C"));
                c.setURIImageSymbol(rs.getString("URL_PHOTO_collection"));
                conn.Close();
                return c;
            }
        } catch (SQLException ex) {
            Logger.getLogger(DAO_Collection.class.getName()).log(Level.SEVERE, null, ex);
        }
        conn.Close();
        return null;
    }
    
}
